package cn.zuzi.mzitu;
import java.io.File;
import java.io.IOException;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import cn.zuzi.mzitu.utils.PicDownThread;
import cn.zuzi.mzitu.utils.PicUtils;
public class DownPicThread extends Thread {

	public PicBean picbean;

	public DownPicThread(PicBean picBean2) {
		this.picbean = picBean2;
	}

	@Override
	public void run() {
		String picBaseUrl = picbean.getPicBaseUrl();
		Document document;
		try {
			document = Jsoup.connect(picBaseUrl).get();
			String first_pic_src = getPicDetailUrl(document);

			String pageNumSti = document.getElementsByClass(picbean.picNumClass).get(0).toString();
			picbean.setPicNum(PicUtils.getPicNum(pageNumSti));

			// 下载第一张图片
			File file = new File(PicUtils.SAVE_FILE, picbean.getPicPubDate() + "/" + picbean.getTitle() + "/");
			if (!file.exists()) {
				file.mkdirs();
			}
			new PicDownThread(picbean.getTitle(), picbean.getPicPubDate(), first_pic_src, 1).start();

			// 下载其余图片
			for (int i = 1; i <= picbean.getPicNum(); i++) {
				Document docume = Jsoup.connect(picBaseUrl + "/" + i).get();
				String picDetailUrl = getPicDetailUrl(docume);
				new PicDownThread(picbean.getTitle(), picbean.getPicPubDate(), picDetailUrl, i + 1).start();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}

	}

	/**
	 * 获取 具体URL
	 * 
	 * @param document
	 * @return
	 */
	private String getPicDetailUrl(Document document) {
		return document.getElementsByClass(picbean.picImgPostion).get(0).getElementsByTag("img").get(0).attr("src");
	}
}
